package com.seo.service.keyword.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.seo.mapper.keyword.KeywordMapper;
import com.seo.pojo.ReturnBody;
import com.seo.service.user.sdk.UserService;
import com.seo.utils.CommonUtil;
import com.seo.utils.KeyWordsIndex;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service("keywordTService")
public class KeywordTServiceImpl extends KeywordServiceImpl {

	@Autowired
	private KeywordMapper keywordMapper;

	@Resource(name = "keywordService")
	private KeywordServiceImpl keywordService;

	@Autowired
	private UserService userService;

	@Value("${keyword.key}")
	private String key;
	@Value("${keyword.shenma.url}")
	private String shenmaUrl;
	@Value("${keyword.so.url}")
	private String soUrl;
	@Value("${keyword.sougou.url}")
	private String sougouUrl;
	@Value("${keyword.baidu.url}")
	private String baiduUrl;

	@PostConstruct
	public void init() {
		log.info("批量上传注册[{}]", "02");
		keywordService.put("02", this);
	}

	@SuppressWarnings("unchecked")
	public ReturnBody saveKeyWord1(Map<String, Object> param, String type) {
		log.info("代理用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		String urlKeyword = param.get("urlKeyword") + "";
		Map<String, Object> user = (Map<String, Object>) param.get("user");
		String createId = param.get("createId") + "";
		String engineCode = param.get("engineCode") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(urlKeyword) || user == null || StringUtils.isEmpty(createId)
				|| StringUtils.isEmpty(engineCode)) {
			return rb.rollback("参数不能为空");
		}

		rb.run(CommonUtil.isUrlKeywordGroup(urlKeyword));
		
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}

		String[] engineCodes = engineCode.split(",");

		List<String> domains = rb.getCollection("urlList", String.class);
		List<String> keywordList = rb.getCollection("keywordList", String.class);
		Map<String, Object> userById = userService.getUserById(Integer.parseInt(user.get("id") + ""));
		if (userById == null) {
			return rb.rollback("用户不存在");
		}
		String parentId = userById.get("parentId")+"";
		if(StringUtils.isEmpty(parentId) || !"0".equals(parentId)) {
			return rb.rollback("用户等级有误，请用新版添加!");
		}
		String price1 = userById.get("price1") + "";
		String price2 = userById.get("price2") + "";
		if (StringUtils.isEmpty(price1) || "0.0000".equals(price1) || StringUtils.isEmpty(price2)
				|| "0.0000".equals(price2)) {
			return rb.rollback("关键词报价为空");
		}
		try {
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
					String kw = keywordList.get(j);
					String url = domains.get(j);
					int num = keywordMapper.getkeyWordConfig(kw);
					Map<String, Object> pa = new HashMap<>();
					String price = "";
					if ("01".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度PC");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("02".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度移动");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("03".equals(engineCodes[i])) {
						pa.put("engineCodes", "360PC");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("04".equals(engineCodes[i])) {
						pa.put("engineCodes", "360移动");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("05".equals(engineCodes[i])) {
						pa.put("engineCodes", "神马");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("06".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗pc");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					if ("07".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗移动");
						if (num != 0) {
							price = price1;
						} else {
							price = price2;
						}
					}
					pa.put("price", price);
					pa.put("keyWord", kw);
					pa.put("userId", user.get("id"));
					if ("01".equals(type)) {
						pa.put("state", "01");
					} else {
						pa.put("state", "00");
					}
					pa.put("keywordIndex", KeyWordsIndex.getKeyWordsInde(kw, key, engineCodes[i]));
					pa.put("createId", createId);
					pa.put("engineCode", engineCodes[i]);
					pa.put("domain", url);
					pa.put("realUserId", user.get("id"));
					int count = keywordMapper.getKeyWordNum(pa);
					if(count > 0) {
						failList.add(pa);
						continue;
					}
					keywordMapper.saveKeyWord(pa);
					successList.add(pa);
					Map<String,Object> m = new HashMap<>();
					m.put("keywords_id", pa.get("id"));
					m.put("parentId", "0");
					m.put("userId", user.get("id"));
					m.put("price", price);
					m.put("create_id", createId);
					keywordMapper.saveKeyWordRelation(m);
				}

			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("代理用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}

	@SuppressWarnings("unchecked")
	public ReturnBody saveKeyWordProxy1(Map<String, Object> param) {
		log.info("代理三方用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> proxyUser = (Map<String, Object>) param.get("proxyUser");
		Map<String, Object> user = (Map<String, Object>) param.get("user");
		String urlKeyword = param.get("urlKeyword") + "";
		String userId = param.get("userId") + "";
		String proxyId = proxyUser.get("id") + "";
		String engineCode = param.get("engineCode") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(urlKeyword) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(proxyId)
				|| StringUtils.isEmpty(engineCode) || user == null) {
			return rb.rollback("参数不能为空");
		}
		
		Map<String, Object> userById = userService.getUserById(Integer.parseInt(userId));
		if(userById == null || userById.isEmpty()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		String parentId = userById.get("parentId")+"";
		if(StringUtils.isEmpty(parentId) || !"0".equals(parentId)) {
			return rb.rollback("用户等级有误，请用新版添加!");
		}
		
		rb.run(CommonUtil.isUrlKeywordGroup(urlKeyword));
		
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		List<String> domains = rb.getCollection("urlList", String.class);
		List<String> keywordList = rb.getCollection("keywordList", String.class);
		String[] engineCodes = engineCode.split(",");
		String price1 = user.get("price1") + "";
		String price2 = user.get("price2") + "";
		if (StringUtils.isEmpty(price1) || "0.0000".equals(price1) || StringUtils.isEmpty(price2)
				|| "0.0000".equals(price2)) {
			return rb.rollback("关键词报价为空");
		}
		try {
			List<Map<String, Object>> keyWordOffer = getKeyWordOffer(keywordList, "01", Integer.parseInt(userId), engineCodes);
			if (keyWordOffer == null || keyWordOffer.size() == 0) {
				return rb.rollback("关键词报价为空");
			}
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
					Map<String, Object> map = keyWordOffer.get(j);

					Map<String, Object> pa = new HashMap<>();
					String keyWords = map.get("keyWord") + "";
					int num = keywordMapper.getkeyWordConfig(keyWords);
					String proxyPrice = "";
					String keywordIndex = "";
					String price = "";
					if ("01".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度PC");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("BaiduPc") + "";
						keywordIndex = map.get("BaiduPcI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("02".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度移动");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("BaiduMobile") + "";
						keywordIndex = map.get("BaiduMobileI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("03".equals(engineCodes[i])) {
						pa.put("engineCodes", "360PC");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("so") + "";
						keywordIndex = map.get("soI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("04".equals(engineCodes[i])) {
						pa.put("engineCodes", "360移动");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("so") + "";
						keywordIndex = map.get("soI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("05".equals(engineCodes[i])) {
						pa.put("engineCodes", "神马");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("shenma") + "";
						keywordIndex = map.get("shenmaI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("06".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗pc");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("SogouPc") + "";
						keywordIndex = map.get("SogouPcI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("07".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗移动");
						if (num == 0) {
							price = price2;
						} else {
							price = price1;
						}
						proxyPrice = map.get("SogouMobile") + "";
						keywordIndex = map.get("SogouMobileI") + "";
						keyWords = map.get("keyWord") + "";
					}
					pa.put("price", price);
					pa.put("proxyPrice", proxyPrice);
					pa.put("keywordIndex", keywordIndex);
					pa.put("keyWord", keyWords);
					pa.put("userId", userId);
					pa.put("realUserId", userId);
					pa.put("proxyId", proxyId);
					pa.put("engineCode", engineCodes[i]);
					pa.put("domain", domains.get(j));
					int count = keywordMapper.getKeyWordNum(pa);
					if(count > 0) {
						failList.add(pa);
						continue;
					}
					keywordMapper.saveKeyWord(pa);
					keywordMapper.saveKeyWordProxy(pa);
					successList.add(pa);
					Map<String,Object> m = new HashMap<>();
					m.put("keywords_id", pa.get("id"));
					m.put("parentId", "0");
					m.put("userId", userId);
					m.put("price", price);
					m.put("create_id", userId);
					keywordMapper.saveKeyWordRelation(m);
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("代理三方用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}
	
	@SuppressWarnings("unchecked")
	public ReturnBody saveKeyWordProxy2(Map<String, Object> param) {
		log.info("代理三方用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		Map<String, Object> proxyUser = (Map<String, Object>) param.get("proxyUser");
		Map<String, Object> user = (Map<String, Object>) param.get("user");
		String urlKeyword = param.get("urlKeyword") + "";
		String userId = param.get("userId") + "";
		String proxyId = proxyUser.get("id") + "";
		String engineCode = param.get("engineCode") + "";
		engineCode = engineCode.substring(0, engineCode.length() - 1);
		if (StringUtils.isEmpty(urlKeyword) || StringUtils.isEmpty(userId)
				|| StringUtils.isEmpty(proxyId) || StringUtils.isEmpty(engineCode) || user == null) {
			return rb.rollback("参数不能为空");
		}
		
		Map<String, Object> userById = userService.getUserById(Integer.parseInt(userId));
		if(userById == null || userById.isEmpty()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		String parentId = userById.get("parentId")+"";
		if(StringUtils.isEmpty(parentId) || !"0".equals(parentId)) {
			return rb.rollback("用户等级有误，请用新版添加!");
		}
		
		rb.run(CommonUtil.isUrlKeywordGroup(urlKeyword));
		
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		
		List<String> domains = rb.getCollection("urlList", String.class);
		List<String> keyWordList = rb.getCollection("keywordList", String.class);
		
		String[] engineCodes = engineCode.split(",");
		String price1 = user.get("price1") + "";
		String price2 = user.get("price2") + "";
		if (StringUtils.isEmpty(price1) || "0.0000".equals(price1) || StringUtils.isEmpty(price2)
				|| "0.0000".equals(price2)) {
			return rb.rollback("关键词报价为空");
		}
		String price11 = proxyUser.get("price1") + "";
		String price22 = proxyUser.get("price2") + "";
		if (StringUtils.isEmpty(price1) || "0.0000".equals(price1) || StringUtils.isEmpty(price2)
				|| "0.0000".equals(price2)) {
			return rb.rollback("关键词报价为空");
		}
		try {
			
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
						String kw = keyWordList.get(j).trim();
						int num = keywordMapper.getkeyWordConfig(kw);
						Map<String, Object> pa = new HashMap<>();
						String price = "";
						String proxyPrice = "";
						if ("01".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度PC");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("02".equals(engineCodes[i])) {
							pa.put("engineCodes", "百度移动");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("03".equals(engineCodes[i])) {
							pa.put("engineCodes", "360PC");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("04".equals(engineCodes[i])) {
							pa.put("engineCodes", "360移动");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("05".equals(engineCodes[i])) {
							pa.put("engineCodes", "神马");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("06".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗pc");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						if ("07".equals(engineCodes[i])) {
							pa.put("engineCodes", "搜狗移动");
							if (num == 0) {
								price = price2;
								proxyPrice = price22;
							} else {
								price = price1;
								proxyPrice = price11;
							}
						}
						pa.put("price", price);
						pa.put("proxyPrice", proxyPrice);
						pa.put("keywordIndex", KeyWordsIndex.getKeyWordsInde(kw, key, engineCodes[i]));
						pa.put("keyWord", kw);
						pa.put("userId", userId);
						pa.put("realUserId", userId);
						pa.put("proxyId", proxyId);
						pa.put("engineCode", engineCodes[i]);
						pa.put("domain", domains.get(j));
						int count = keywordMapper.getKeyWordNum(pa);
						if(count > 0) {
							failList.add(pa);
							continue;
						}
						keywordMapper.saveKeyWord(pa);
						keywordMapper.saveKeyWordProxy(pa);
						successList.add(pa);
						Map<String,Object> m = new HashMap<>();
						m.put("keywords_id", pa.get("id"));
						m.put("parentId", "0");
						m.put("userId", userId);
						m.put("price", price);
						m.put("create_id", userId);
						keywordMapper.saveKeyWordRelation(m);
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("代理三方用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}

	/**
	 * 普通用户添加关键词
	 * 
	 * @param param
	 *            param
	 * @return String
	 */
	public ReturnBody saveKeyWordAdmin(Map<String, Object> param) {
		log.info("普通用户添加关键词开始--- param={}", param);
		ReturnBody rb = ReturnBody.init();
		String urlKeyword = param.get("urlKeyword") + "";
		String userId = param.get("userId") + "";
		String createId = param.get("createId") + "";
		String engineCode = param.get("engineCode") + "";
		Map<String, Object> userById = userService.getUserById(Integer.parseInt(userId));
		if(userById == null || userById.isEmpty()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}
		String parentId = userById.get("parentId")+"";
		if(StringUtils.isEmpty(parentId) || !"0".equals(parentId)) {
			return rb.rollback("用户等级有误，请用新版添加!");
		}

		if (StringUtils.isEmpty(urlKeyword) || StringUtils.isEmpty(userId) || StringUtils.isEmpty(createId)
				|| StringUtils.isEmpty(engineCode)) {
			return rb.rollback("参数不能为空");
		}

		rb.run(CommonUtil.isUrlKeywordGroup(urlKeyword));
		
		if (!rb.isSuccess()) {
			rb.getResult().setIsRollBack("01");
			return rb;
		}

		List<String> domains = rb.getCollection("urlList", String.class);
		List<String> keywordList = rb.getCollection("keywordList", String.class);

		engineCode = engineCode.substring(0, engineCode.length() - 1);

		String[] engineCodes = engineCode.split(",");
		try {
			List<Map<String, Object>> keyWordOffer = getKeyWordOffer(keywordList, "00", 1, engineCodes);
			if (keyWordOffer == null || keyWordOffer.size() == 0) {
				return rb.rollback("关键词报价为空");
			}
			List<Map<String, Object>> successList = new ArrayList<>();
			List<Map<String, Object>> failList = new ArrayList<>();
			for (int i = 0; i < engineCodes.length; i++) {
				for (int j = 0; j < domains.size(); j++) {
					Map<String, Object> map = keyWordOffer.get(j);

					Map<String, Object> pa = new HashMap<>();
					String price = "";
					String keywordIndex = "";
					String keyWords = "";
					if ("01".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度PC");
						price = map.get("BaiduPc") + "";
						keywordIndex = map.get("BaiduPcI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("02".equals(engineCodes[i])) {
						pa.put("engineCodes", "百度移动");
						price = map.get("BaiduMobile") + "";
						keywordIndex = map.get("BaiduMobileI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("03".equals(engineCodes[i])) {
						pa.put("engineCodes", "360PC");
						price = map.get("so") + "";
						keywordIndex = map.get("soI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("04".equals(engineCodes[i])) {
						pa.put("engineCodes", "360移动");
						price = map.get("so") + "";
						keywordIndex = map.get("soI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("05".equals(engineCodes[i])) {
						pa.put("engineCodes", "神马");
						price = map.get("shenma") + "";
						keywordIndex = map.get("shenmaI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("06".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗pc");
						price = map.get("SogouPc") + "";
						keywordIndex = map.get("SogouPcI") + "";
						keyWords = map.get("keyWord") + "";
					}
					if ("07".equals(engineCodes[i])) {
						pa.put("engineCodes", "搜狗移动");
						price = map.get("SogouMobile") + "";
						keywordIndex = map.get("SogouMobileI") + "";
						keyWords = map.get("keyWord") + "";
					}
					pa.put("price", price);
					pa.put("keywordIndex", keywordIndex);
					pa.put("keyWord", keyWords);
					pa.put("userId", userId);
					pa.put("createId", createId);
					pa.put("engineCode", engineCodes[i]);
					pa.put("domain", domains.get(j));
					pa.put("state", "00");
					pa.put("realUserId", userId);
					int count = keywordMapper.getKeyWordNum(pa);
					if(count > 0) {
						failList.add(pa);
						continue;
					}
					keywordMapper.saveKeyWord(pa);
					successList.add(pa);
					Map<String,Object> m = new HashMap<>();
					m.put("keywords_id", pa.get("id"));
					m.put("parentId", "0");
					m.put("userId", userId);
					m.put("price", price);
					m.put("create_id", createId);
					keywordMapper.saveKeyWordRelation(m);
				}
			}
			rb.put("successList", successList);
			rb.put("failList", failList);
		} catch (Exception e) {
			log.info("普通用户添加关键词异常--- e={}", e);
			return rb.rollback("关键词域名重复");
		}
		return rb.success();
	}

}